<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Articles Manager
 * @author	Tran Van Thanh
 * @mail	thanhtran@vietnambiz.com
 * @date	06.09.2011
 */
require_once('admin'.EXT);

class Articles extends Admin {

	function __construct()
	{
		parent::__construct();
		$this->load->model(array('articles_model'));
		$this->load->helper(array('upload','text'));			
	}

	function index()
	{
		$page = (isset($_GET['p']) && is_numeric($_GET['p'])) ? $_GET['p'] : 1;

        if(isset($_GET['status'])) {
            $status = ($_GET['status'] == 'active') ? 'yes' : 'no';
            $this->db->where('status', $status);
        }		
		if(isset($_GET['keyword'])) {    
			$keyword = $_GET['keyword'];
			$keyword = strip_tags($keyword);
			if($keyword == 'keyword')
			{
				$keyword = "";
			}
			else
			{
				$this->db->like('title', $keyword)
            		 ->or_like('description', $keyword)
            		 ->or_like('contents', $keyword)
            		 ->or_like('author', $keyword)
            		 ->or_like('source', $keyword);
			}
        }

		$this->data['articles'] 	= $this->articles_model->get_articles($page != "" ? $page : 1);
		$this->data['page'] 		= $page;

    	$conf =	array(
    		'base_url'		=> admin_url($this->router->class).'/',
    		'total_rows'	=> $this->articles_model->count_all(),
    		'per_page'		=> $this->config->item('articles', 'limit'),
    		'cur_page'		=> $page,
    	);
    	$this->pagination->initialize($conf);
    	$this->data['pagnav'] = $this->pagination->display_query_string();

		if($this->input->is_ajax_request()) {
			$this->load->view('articles/list', $this->data);
		}
		else {
			$this->data['tpl_file']	= 'articles/index';
			$this->load->view('layout/default', $this->data);
		}
	}

	function add()
	{		
		if($_SERVER['REQUEST_METHOD'] == 'POST') 
		{
			$this->form_validation->set_message('required', '%s không hợp lệ!');
    		$this->form_validation->set_rules('txt_title', 'Tiêu đề', 'required|trim|xss_clean');

    		if($this->form_validation->run() == TRUE)
            {            	
            	$title 	= $this->input->post('txt_title');
                //{
                    $album_dir = 'uploads/news/';
                    create_dir($album_dir);
                    $config['upload_path'] = $album_dir;
            		$config['allowed_types'] = 'gif|jpg|png';
            		$config['max_size']	= '100';
            		$config['max_width']  = '1024';
            		$config['max_height']  = '768';
                    $config['encrypt_name'] = true;
                    $this->load->library('upload', $config);
            		$data = array(
            			'title'				=> strip_tags($title),
            			'title_link'		=> ascii_link($title,'-'),
            			'description'		=> strip_tags($this->input->post('txt_desc')),
            			'contents'			=> $this->input->post('txt_content'),
            			'author'			=> strip_tags($this->input->post('txt_author')),
            			'source'			=> strip_tags($this->input->post('txt_source')),            			         		
            			'date_create'		=> date('Y-m-d H:i:s'),     
            			'status'			=> $this->input->post('status')
            		);
            		
                    if($this->upload->do_upload('image')){
                        $img = $this->upload->data();
                        $data['images_thumb']    =   $album_dir.$img['file_name'];
                        $articles_id = $this->articles_model->insert($data);
                    }
                    else
                    {
                        die($this->upload->display_errors());
                    }
            		

            		die('yes');           	
            }
            else {
            	die(validation_errors());
            }
		}
		
		$this->load->view('articles/add', $this->data);
	}

	function edit($articles_id = null)
	{		
		$articles = $this->articles_model->get($articles_id);

		if($_SERVER['REQUEST_METHOD'] == 'POST') 
		{
    		$this->form_validation->set_rules('txt_title', 'Tiêu đề', 'required|trim|xss_clean');

    		if($this->form_validation->run() == TRUE)
            {       
            	$title 	= $this->input->post('txt_title');

            	$data_articles = array(
            		'title'				=> strip_tags($title),
            		'title_link'		=> ascii_link($title,'-'),
            		'description'		=> strip_tags($this->input->post('txt_desc')),
            		'contents'			=> $this->input->post('txt_content'),
            		'author'			=> strip_tags($this->input->post('txt_author')),
            		'source'			=> strip_tags($this->input->post('txt_source')),            	          		          			        		
            		'status'			=> $this->input->post('status')
            	);            	
            	
                if($_FILES['image']['name'] != '')
                {
                    $album_dir = 'uploads/news/';
                    create_dir($album_dir);
                    $config['upload_path'] = $album_dir;
            		$config['allowed_types'] = 'gif|jpg|png|jpeg';
            		$config['max_size']	= '100';
                    $config['max_width']  = '1024';
            		$config['max_height']  = '768';
                    $config['encrypt_name'] = true;
                    $this->load->library('upload', $config);
                    if($this->upload->do_upload('image')){
                        $img = $this->upload->data();
                        $data_articles['images_thumb']    =   $album_dir.$img['file_name'];
                        $articles_id = $this->articles_model->update($articles->id,$data_articles);
                    }
                    else{
                        die($this->upload->display_errors());
                    }
                }  
                else{
                    //ko cap nhat lai anh
                }      	
            	die('yes');            	            	            	
            }
            else {
            	die(validation_errors());
            }
		}

		$this->data['articles'] = $articles;
		$this->load->view('articles/edit', $this->data);
	}
	
    function delete($articles_id = null)
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
        	$article = $this->articles_model->get_by('id',$articles_id);

            $this->articles_model->delete($articles_id);
           	unlink('uploads/news/'.$article->images_thumb);

            die('yes');
        }
    }

	function do_action()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST') {

			$id_list = $this->input->post('id');
			$action = $this->input->post('action');

			if($action == 'delete') {
				$this->delete($id_list);
			}
			elseif($action == 'pending') {
				$this->articles_model->update_many($id_list, array('status' => 'no'));
			}
			elseif($action == 'active') {
				$this->articles_model->update_many($id_list, array('status' => 'yes'));
			}

			die('yes');
		}
	}

	function change_status()
	{
		$articles_id = $this->input->post('articles_id');
		$status 	 = $this->input->post('status');

		$this->articles_model->update($articles_id, array('status' => $status));
		die('yes');
	}	

	function load_row($articles_id = null)
	{		
		$this->data['articles'] = $this->articles_model->get($articles_id);
		$this->load->view('articles/row', $this->data);
	}

	function _check_upload()
	{
		$count = 0;
		if(isset($_FILES['images'])) {
	    	$tt = count($_FILES['images']['name']);
	    	for($i = 0; $i < $tt; $i++) {
	    	    if($_FILES['images']['error'][$i] === 0) $count++;
	    	}
	    }

	    return ($count > 0) ? true : false;
	}

	function _create_thumb($img_path = '')
	{
		$sizes = config_item('thumb_size');
		$this->load->helper('string');
		$pathinfo = pathinfo($img_path);
		$new_name = $pathinfo['basename'];
		
		if($img = $this->db->from('images_news')->where('img_path',$pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name)->get()->row())
		{
			$temp	=	explode('.',$pathinfo['basename']);
			$new_name	=	$temp[0].date('-his-mdy').'.'.$pathinfo['extension'];
		}

		rename($img_path, $pathinfo['dirname'].'/'.$new_name);

        include_once (config_item('phpThumb_dir')."ThumbLib.inc.php");

        $options = array(
		    'resizeUp' 		=> true,
		    'jpegQuality'	=> 88,
        );

		
		foreach($sizes as $size)
		{
			$thumb_dir  = $pathinfo['dirname'].'/thumb_'.$size;
			create_dir($thumb_dir);

			$t_size = explode('-', $size);

		    $thumb 	= PhpThumbFactory::create($pathinfo['dirname'].'/'.$new_name, $options);

		    $thumb->adaptiveResize($t_size[0] + 5, $t_size[1] + 5);
		    $thumb->cropFromCenter($t_size[0], $t_size[1]);
		    $thumb->save($thumb_dir.'/'.$new_name, 'jpg');
		}


		return $pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name;
	}
	
	function _delete_image($img_path = '')
	{
    	$filename = basename($img_path);
        $sizes = config_item('thumb_size');

    	foreach($sizes as $size) {
    		$path = str_replace($sizes[0], $size, $img_path);
    		if(is_file($path)) unlink($path);
    	}
    	$path = str_replace('/thumb_'.$sizes[0], '', $img_path);
    	if(is_file($path)) unlink($path);
	}
	
	function deleteAll($directory, $empty = false) { 
    if(substr($directory,-1) == "/") { 
        $directory = substr($directory,0,-1); 
    } 

    if(!file_exists($directory) || !is_dir($directory)) { 
        return false; 
    } elseif(!is_readable($directory)) { 
        return false; 
    } else { 
        $directoryHandle = opendir($directory); 
        
        while ($contents = readdir($directoryHandle)) { 
            if($contents != '.' && $contents != '..') { 
                $path = $directory . "/" . $contents; 
                
                if(is_dir($path)) { 
                    deleteAll($path); 
                } else { 
                    unlink($path); 
                } 
            } 
        } 
        
        closedir($directoryHandle); 

        if($empty == false) { 
            if(!rmdir($directory)) { 
                return false; 
            } 
        } 
        
        return true; 
    } 
} 
	
	 
}

